﻿#region Usings

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Match.Foundation.Business.Classes;
using Match.Foundation.Config.Classes;
using Match.Foundation.Enums;
using Match.TimingApplication.Classes;

#endregion

namespace Match.TimingApplication.Forms
{
    public partial class frmMain : Form
    {
        private frmProgrammConfig _frmProgrammConfig;
        private frmRaceStart _frmRaceStart;
        private Queue<Participant> _IncominStarter;
        private Queue<TransferLogItem> _LogMessageQueue;
        private Queue<StarterInfo> _StarterInfoQueue;
        private TransferManager _Transfermanager;

        #region Constructor

        public frmMain()
        {
            InitializeComponent();

            AppConfig.Initialize(Application.StartupPath + @"\Config\Config.ini");

            _Transfermanager = new TransferManager();
            _Transfermanager.OnIncomingStarterInfo += new IncomingStarterInfo(_Transfermanager_OnIncomingStarterInfo);
            _LogMessageQueue = new Queue<TransferLogItem>();
            _IncominStarter = new Queue<Participant>();
            _StarterInfoQueue = new Queue<StarterInfo>();
        }

        #endregion

        #region FormEvents

        private void beendenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void timerOnlineCheck_Tick(object sender, EventArgs e)
        {
            labelQueueCount.Text = _Transfermanager.ItemsInQueue.ToString();

            labelTime.Text = DateTime.Now.ToString();
            labelActualDate.Text = DateTime.Now.ToLongDateString();

            if (File.Exists(AppConfig.GetStringValue(ConfigEntry.DatabasePath)))
            {
                pictureBoxOnline.Visible = true;
                pictureBoxOffline.Visible = false;
            }
            else
            {
                pictureBoxOnline.Visible = false;
                pictureBoxOffline.Visible = true;
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (
                MessageBox.Show("Möchten Sie das Programm wirklich schließen?", "Schließen", MessageBoxButtons.YesNo,
                                MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                _Transfermanager.Stop();
            }
        }

        private void systemeinstellungenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _frmProgrammConfig = new frmProgrammConfig();
            _frmProgrammConfig.ShowDialog();
            _frmProgrammConfig.BringToFront();
        }

        private void timerRefresh_Tick(object sender, EventArgs e)
        {
            labelActualTime.Text = DateTime.Now.ToLongTimeString() + "." + DateTime.Now.Millisecond.ToString("000");
            if (_StarterInfoQueue.Count > 0)
            {
                StarterInfo Info = _StarterInfoQueue.Dequeue();
                for (int i = 0; i < listViewTimes.Items.Count; i++)
                {
                    if (listViewTimes.Items[i].Tag != null)
                    {
                        StarterTimeItem TimeItem = (StarterTimeItem) listViewTimes.Items[i].Tag;
                        if (TimeItem.TimeID == Info.LastTimeID)
                        {
                            listViewTimes.Items[i] =
                                new ListViewItem(
                                    new string[]
                                        {
                                            TimeItem.Time.ToLongTimeString() + "." +
                                            TimeItem.Time.Millisecond.ToString("000"), TimeItem.StartNumber,
                                            Info.FirstName + " " + Info.LastName, Info.Dictance, Info.StartClass
                                        });
                            listViewTimes.Items[i].Tag = TimeItem;
                            break;
                        }
                    }
                }
            }
            while (listViewTimes.Items.Count > 100)
            {
                lock (listViewTimes)
                {
                    listViewTimes.Items.RemoveAt(listViewTimes.Items.Count - 1);
                }
            }
        }

        private void buttonRegister_Click(object sender, EventArgs e)
        {
            if (textBoxStartNumber.Text.Trim() != "")
            {
                StarterTimeItem Item = new StarterTimeItem(textBoxStartNumber.Text, DateTime.Now, TimingMode.Register);
                _Transfermanager.RegisterStartNumber(Item);
                AddStartTimeItemToListView(Item);
                textBoxStartNumber.Clear();
                textBoxStartNumber.Focus();
            }
        }

        private void buttonDeleteCheckedTimes_Click(object sender, EventArgs e)
        {
            List<ListViewItem> DelItems = new List<ListViewItem>();
            lock (listViewTimes)
            {
                for (Int32 i = 0; i < listViewTimes.Items.Count; i++)
                {
                    if (listViewTimes.Items[i].Checked)
                    {
                        StarterTimeItem Item = (StarterTimeItem) listViewTimes.Items[i].Tag;


                        if (
                            MessageBox.Show(
                                "Möchten Sie die Zeit " + Item.Time.ToLongTimeString() + "." +
                                Item.Time.Millisecond.ToString() + " für Startnummer " + Item.StartNumber +
                                " wirklich löschen?", "Bestätigen", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                            DialogResult.Yes)
                        {
                            Item.TimingMode = TimingMode.Unregister;
                            _Transfermanager.RegisterStartNumber(Item);
                            DelItems.Add(listViewTimes.Items[i]);
                        }
                    }
                    listViewTimes.Items[i].Checked = false;
                }
            }
            foreach (ListViewItem Item in DelItems)
            {
                listViewTimes.Items.Remove(Item);
            }
        }

        private void wettkampfstartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _frmRaceStart = new frmRaceStart(_Transfermanager);
            _frmRaceStart.ShowDialog();
            _frmRaceStart.BringToFront();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (Int32 i = 1; i <= 50; i++)
            {
                Thread.Sleep(50);
                Application.DoEvents();
                textBoxStartNumber.Text = i.ToString();
                Application.DoEvents();
                Thread.Sleep(50);
                Application.DoEvents();
                buttonRegister_Click(sender, e);
                Application.DoEvents();
            }
        }

        #endregion

        #region Private Methods

        private void AddStartTimeItemToListView(StarterTimeItem Item)
        {
            listViewTimes.Items.Insert(0,
                                       new ListViewItem(
                                           new String[]
                                               {
                                                   Item.Time.ToLongTimeString() + "." +
                                                   Item.Time.Millisecond.ToString("000"), Item.StartNumber
                                               })).Tag = Item;
        }

        private void textBoxStartNumber_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                buttonRegister_Click(sender, e);
            }
        }

        private void _Transfermanager_OnIncomingStarterInfo(StarterInfo StarterInfo)
        {
            _StarterInfoQueue.Enqueue(StarterInfo);
        }

        #endregion

        private void datenimportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmLoadTransferdisk LoadDisk = new frmLoadTransferdisk();
            LoadDisk.ShowDialog();
        }

        private void datenexporToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDataExport DataExport = new frmDataExport();
            DataExport.ShowDialog();
        }

        private void frmMain_Shown(object sender, EventArgs e)
        {
            textBoxStartNumber.Focus();
        }
    }
}